<template>
  <page-container>
    <search-form
      v-model="searchForm"
      :searchColumns="searchColumns"
      :searchOptions="{ menuSpan: 8 }"
      @on-search="handleSearch">
      <template v-slot:newBtn>
        <el-button
          type="primary"
          @click="handelAddUrl('add')">
          增加计划
        </el-button>
      </template>
    </search-form>

    <avue-table
      :dataList="dataList"
      :loading="loading"
      :page="page"
      :tableColumns="tableColumns"
      :tableOptions="{ menuWidth: 80 }"
      @onPageChange="onPageChange">
      <template v-slot:menu="{ row }">
        <el-button
          type="primary"
          icon="el-icon-edit"
          circle
          @click="handelAddUrl('edit', row)">
        </el-button>
      </template>
      <template v-slot:img_url="{ row }">
        <span v-if="row.img_url === ''">--</span>
        <el-image
          v-else
          style="width: 50px; height: 50px"
          :src="imgUrl + row.img_url"
          :fit="fit"
          :preview-src-list="srcList"
          @click="clickImage(row)">
          <!-- <div
            slot="error"
            class="image-slot">
            <i class="el-icon-picture-outline"></i>
          </div> -->
        </el-image>
      </template>
    </avue-table>
    <el-dialog
      :title="type === 'edit' ? '编辑计划' : '新增计划'"
      :close-on-click-modal="false"
      :visible.sync="outerVisible"
      :show-close="false">
      <avue-form
        ref="forms"
        :option="option"
        v-model="dialogForm"
        @submit="handleSubmit"
        @reset-change="close"></avue-form>
    </el-dialog>
  </page-container>
</template>

<script>
import tableMixins from '@/mixins/table'
import { deepClone } from '@/utils'
import { mapGetters } from 'vuex'
import { getMovieQuery, handleMovieChil } from '@/api/movie'
import { queryCrowdPush, addCrowdPush, editCrowdPush, queryCrowdRule } from '@/api/userManage'
import { searchColumns, tableColumns } from './config/table-config'
import { allForm } from './config/dialog-config'
import { set } from 'vue'

export default {
  mixins: [tableMixins],
  data() {
    return {
      fit: 'cover',
      title: '',
      type: '',
      outerVisible: false,
      srcList: [],
      dataList: [],
      movieChilist: [],
      push_time: [],
      childList: [],
      userGroupList: [],
      pages: [
        { value: 0, label: '首页' },
        { value: 1, label: 'for you' },
        { value: 2, label: 'top up充值' },
        { value: 3, label: '福利中心' },
      ],
      searchForm: {
        dateRange: [this.$startStamp(new Date()), this.$endStamp(new Date())],
      },
      dialogForm: {
        push_time: '',
        dateTip: [],
      },
    }
  },
  computed: {
    ...mapGetters(['commonData']),
    userList() {
      return this.commonData?.userList ?? []
    },
    imgUrl() {
      return `${process.env.VUE_APP_CND}`
    },
    option() {
      return {
        emptyText: '取消',
        span: 24,
        labelWidth: 120,
        column: this.allForm,
        callback: async ({ data, close }) => {
          this.resData = []
          if (this.type === 'edit') {
            this.resData = await editCrowdPush(data)
          } else {
            this.resData = await addCrowdPush(data)
          }
          if (this.resData.code === 0) {
            this.$message.success(`${this.type === 'edit' ? '编辑' : '新增'}成功`)
          }
          this.getList()
          close()
        },
      }
    },
    allForm,
    searchColumns,
    tableColumns,
  },
  watch: {},
  methods: {
    fetchMethod: queryCrowdPush,
    // 查询参数格式化
    formatSearch() {
      const searchParams = deepClone(this.searchForm)
      const [start, end] = this.searchForm.dateRange
      searchParams.start = start && this.$dayjs(this.$startStamp(start)).unix()
      searchParams.end = end && this.$dayjs(this.$endStamp(end)).unix()

      searchParams.film_id = this.$route.query.id
      delete searchParams.dateRange
      return searchParams
    },
    clickImage(row) {
      this.srcList = []
      const imgUrl = `${process.env.VUE_APP_CND + row?.img_url}`
      this.srcList.push(imgUrl)
    },
    handelAddUrl(type, row) {
      this.title = type
      this.push_time = []
      this.type = type
      this.outerVisible = true
      this.dialogForm = {
        dateTip: [],
      }
      if (type === 'edit') {
        this.dialogForm = deepClone(row)
        this.dialogForm.user_ids = row?.user_ids?.join(',')
        this.dialogForm.push_time = row?.push_time[0] * 1000
        this.dialogForm.dateTip = row?.push_time?.map(item => this.$formatTime(item))
      }
    },
    async handleSubmit(form, done) {
      const data = deepClone(this.dialogForm)

      const newDate = data.dateTip?.map(item => this.$dayjs(item).unix().valueOf())
      const t_day = [...new Set(newDate)]
      const parms = {
        ...data,
        push_time: JSON.stringify(t_day),
        crowd_rule_ids: JSON.stringify(data?.crowd_rule_ids?.sort()),
      }

      delete parms.dateTip
      delete parms.crowd_rule_name
      let res = {}
      if (this.type === 'add') {
        res = await addCrowdPush(parms)
      } else {
        res = await editCrowdPush(parms)
      }
      if (res?.code === 0) {
        this.$message.success('提交成功！')
        this.clean()
        this.outerVisible = false
        this.getList()
        done()
      }
      this.getList()
      done()
    },
    close() {
      this.outerVisible = false
    },
    clean() {},
    async getUserGroup() {
      const { data } = await queryCrowdRule()
      this.userGroupList = data?.list?.map(item => {
        return {
          value: item?.id,
          label: item?.name,
        }
      })
    },
    async getMovieQuery() {
      const { data } = await getMovieQuery({ status: 2, page: 1, page_size: 100 })
      this.movieList = data?.list?.map(item => {
        return {
          id: item?.id,
          name: item?.name,
        }
      })
    },
    async getMovieChil(id) {
      const { data } = await handleMovieChil({ film_id: id || 0, free: 1 })
      this.movieChilist = data?.list.map(item => {
        return {
          id: item?.id,
          episode_no: item?.episode_no,
        }
      })
    },
  },
  mounted() {
    this.getMovieQuery()
    this.handleSearch()
    this.getUserGroup()
  },
}
</script>

<style lang="scss" scoped>
.movieName {
  font-weight: 600;
  font-size: 16px;
}
</style>
